package demo.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import demo.dao.WeiboDao;
import demo.entity.Weibo;

public class WeiboDaoImpl extends GenericDaoImpl<Weibo, Long> implements WeiboDao {

	@SuppressWarnings("unchecked")
	public List<Object[]> queryWeiboByUserId(int id, String type) {
		
		String queryString = 
			"select w.id, w.content, w.time, w.picture, w.client, w.userid, w.forwardid, u.nick, u.avatar" +
			" from user u, weibo w" +
			" where u.id=w.userid and u.id=" + id;
		if(type.equals("home")) {
			queryString +=
				" UNION " +
				"select w.id, w.content, w.time, w.picture, w.client, w.userid, w.forwardid, u.nick, u.avatar" +
				" from user u, weibo w" +
				" where u.id=w.userid and u.id in (" +
				"select f.followid" +
				" from Follow f" +
				" where f.userid=" + id + ")" +
				" order by time";
		}
		Session session = getHibernateTemplate().getSessionFactory().openSession();
		Query query = session.createSQLQuery(queryString);
		List<Object[]> list = query.list();
		session.close();
		return list;
		
	}
	
	@SuppressWarnings("unchecked")
	public List<Object[]> queryWeiboByWeiboId(long id) {
		String queryString = "select w.id, w.content, w.time, w.picture, w.client, w.userid, w.forwardid, u.nick, u.avatar" +
		" from User u, Weibo w" +
		" where u.id=w.userid and w.id=" + id + 
		" order by w.time desc";
		return getHibernateTemplate().find(queryString);
	}
	
	@SuppressWarnings("unchecked")
	public List<Object[]> queryWeiboByWeiboContent(String content) {
		String queryString = "select w.id, w.content, w.time, w.picture, w.client, w.userid, w.forwardid, u.nick, u.avatar" +
		" from User u, Weibo w" +
		" where u.id=w.userid and w.content like '%" + content + "%'" +
		" order by w.time desc";
		return getHibernateTemplate().find(queryString);
	}
	
	@SuppressWarnings("unchecked")
	public List<Object[]> queryForwardByWeiboId(long id) {
		String queryString = 
			"select w.id as weiboid, w.content, w.time, w.picture, w.client, w.forwardid, u.id as userid, u.nick, u.avatar" +
			"	from Weibo w, User u" +
			"	where find_in_set(w.id, getParentList("+id+")) and u.id=w.userid" +
			"	order by w.time desc";
		//通过HibernateDaoSupport取得一个Hibernate的Session的方式：
		Session session = getHibernateTemplate().getSessionFactory().openSession();
		Query query = session.createSQLQuery(queryString);//Hibernate的原生（本地）SQL查询，以前的事HQL
		List<Object[]> list = query.list();
		session.close();
		return list;
	}
}
